<?php

require_once 'SecurityController.php';

class IndexController extends SecurityController
{

    public function init()
    {
        parent::init();
        $this->isSomeOne(true);
    }

    /**
     * Show welcome
     * if isn't admin and isn't a granja in session, request for one
     */
    public function indexAction()
    {
        if (!$this->isAdmin() && $this->getGranja() == null) {
            $mapper = new Application_Model_UsuarioGranjaMapper();
            $granjas = $mapper->fetchByUsuario($this->getUser()->getId());
            if (count($granjas) > 1) {
                $this->_redirect('/index/select-granja');
            } else {
                $mapper = new Application_Model_GranjaMapper();
                $this->setGranja($mapper->find($granjas[0]->getGranjaId()));
            }
        }
    }

    public function selectGranjaAction()
    {
        if ($this->getRequest()->isPost()) {
            $id_granja = $this->getRequest()->getParam('id_granja');
            $mapper = new Application_Model_GranjaMapper();
            $this->setGranja($mapper->find($id_granja));
            $this->_redirect('/');
        } else if (!$this->isAdmin()) {
            $mapper = new Application_Model_UsuarioGranjaMapper();
            $this->view->granjas = $mapper->fetchByUsuario($this->getUser()->getId());
        }
    }


}



